<?php
/**
 * Created by PhpStorm.
 * User: venki
 * Date: 2023/12/16
 * Time: 16:25
 */

namespace app\modelFilter;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;

class Filter extends Model
{
    protected $query;

    /**
     * @param       $query
     * @param array $config
     */
    public function __construct($query, array $config = [])
    {
        $this->query = $query;
        parent::__construct($config);
    }

    /**
     * @explain description function feature
     * @return void
     * @maxim   from focus to execute
     * @author  venki.chen 2023/12/18 17:03
     */
    public function applyFilters(): void
    {
        foreach ($this->attributes() as $attribute) {
            $value = Yii::$app->request->get($attribute);
            if ($value !== null) {
                $snakeToCamel = function ($str) {
                    if (str_contains($str, '_')) {
                        $str = ucwords(str_replace('_', ' ', $str));
                    } else {
                        $str = ucfirst($str);
                    }
                    return str_replace(' ', '', $str);
                };
                $method       = 'filterBy' . $snakeToCamel($attribute);
                if (method_exists($this, $method)) {
                    $this->$method($value);
                } else {
                    $this->query->andFilterWhere(['=', $attribute, $value]);
                }
            }
        }
    }
}